package com.niit.controller;

import com.niit.entity.Message;
import com.niit.entity.MessageObject;
import com.niit.entity.User;
import com.niit.service.MessageService;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpSession;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.http.ResponseEntity;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import java.util.List;

/**
 * @author 张月
 * @apiNote
 */
@RestController
@RequestMapping("/api/messages")
public class MessageController {
    @Resource
    private MessageService messageService;
    @GetMapping("/startChat")
    public String startChat(
            @RequestParam Integer senderId,
            @RequestParam Integer receiverId) {

        // 重定向到聊天页面
        return "redirect:/api/messages/chat?senderId=" + senderId + "&receiverId=" + receiverId;
    }

    @PostMapping("/contacts")
    public List<Message> getContacts(@RequestParam Integer id) {
        return messageService.findBySenderId(id);
    }

    @GetMapping("/findOrCreateMessageObject")
    public MessageObject findOrCreateMessageObject(@RequestParam Integer senderId, @RequestParam Integer receiverId) {
        return messageService.findOrCreateMessageObject(senderId, receiverId);
    }

    //发送消息
    @PostMapping("/send")
    public ResponseEntity<?> sendMessage(@RequestBody Message message) {
        try {
            Message sentMessage = messageService.sendMessage(message);
            return ResponseEntity.ok(sentMessage);
        } catch (Exception e) {
            return ResponseEntity.badRequest().body("发送消息失败");
        }
    }
    //获取聊天消息
    @GetMapping("/get")
    public ResponseEntity<List<Message>> getChatMessages(
            @RequestParam Integer senderId,
            @RequestParam Integer receiverId) {
        List<Message> messages = messageService.getChatMessages(senderId, receiverId);
        return ResponseEntity.ok(messages);
    }
    @GetMapping("/checkBlockStatus")
    public ResponseEntity<Boolean> checkBlockStatus(
            @RequestParam Integer senderId,
            @RequestParam Integer receiverId) {
        boolean isBlocked = messageService.checkBlockStatus(senderId, receiverId);
        return ResponseEntity.ok(isBlocked);
    }
    //标记为已读
    @PostMapping("/read/{messageId}")
    public ResponseEntity<Void> markAsRead(@PathVariable Integer messageId) {
        messageService.markAsRead(messageId);
        return ResponseEntity.ok().build();
    }
    //撤回消息
    @PostMapping("/recall/{messageId}")
    public ResponseEntity<Void> recallMessage(@PathVariable Integer messageId) {
        messageService.deleteMessage(messageId);
        return ResponseEntity.ok().build();
    }
}